package com.zzzzzz.config;

import javax.inject.Inject;
import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class DataConfig {
	
	@Inject
	private DataSource dataSource;
	
	@Bean
	public JdbcTemplate jdbcTemplate() {
		return new JdbcTemplate(dataSource);
	}
	
	@Bean
	public NamedParameterJdbcTemplate jt() {
		return new NamedParameterJdbcTemplate(dataSource);
	}
	
	@Bean
	public PlatformTransactionManager transactionManager() {
		return new DataSourceTransactionManager(dataSource);
	}

	@Configuration
	static class Standard {

		@Inject
		private Environment environment;

		@Bean
		public DataSource dataSource() {
			BasicDataSource basicDataSource = new BasicDataSource();
			basicDataSource.setDriverClassName(environment.getProperty("jdbc.driver"));
			basicDataSource.setUrl(environment.getProperty("jdbc.url"));
			basicDataSource.setUsername(environment.getProperty("jdbc.username"));
			basicDataSource.setPassword(environment.getProperty("jdbc.password"));
			basicDataSource.setMaxActive(Integer.parseInt(environment.getProperty("dbcp.maxActive")));
			basicDataSource.setMaxIdle(Integer.parseInt(environment.getProperty("dbcp.maxIdle")));
			//basicDataSource.setDefaultAutoCommit(false);
			basicDataSource.setTimeBetweenEvictionRunsMillis(3600000);
			basicDataSource.setMinEvictableIdleTimeMillis(3600000);
			
			return basicDataSource;
		}
		
	}
}